package com.example.demo;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;


/**
 * 2019/8/19
 * 主要通过代码去实现并发编程，但是这个是线程不安全的
 */
@Slf4j
public class ConcurrentTest {

    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    public static int count = 0;

    public static void add(){
        count++;
    }

    /**
     * 创建线程池
     * 创新信号量，创建计数器，当计数器减少至零的时候打印最终的计数
     * 循环5000次，并执行线程执行的方法，200次一起执行并发，最终看看线程是否安全
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i=0; i< clientTotal; i++){
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                    countDownLatch.countDown();//忘记加这句话了，会让程序无限等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        countDownLatch.await();
        log.info("count:{}" + count);
    }

}
